package com.chwn.curiousdiary.ui.user.presenter;

import android.text.TextUtils;

import com.chwn.curiousdiary.DiaryApplication;
import com.chwn.curiousdiary.api.NetWork;
import com.chwn.curiousdiary.bean.StoryBean;
import com.chwn.curiousdiary.gloable.Constant;
import com.chwn.curiousdiary.ui.user.contract.CollectionContract;
import com.chwn.harulib.mvp.rx.HttpResult;
import com.chwn.harulib.mvp.rx.HttpResultException;
import com.chwn.harulib.mvp.rx.RxSchedulers;

import java.util.List;

import rx.Observer;

/**
 * Created by Myshikin on 2017/4/25.
 */

public class CollectionPresenter extends CollectionContract.Presenter {

    private Observer<HttpResult<List<StoryBean>>> collectionObserver = new Observer<HttpResult<List<StoryBean>>>() {
        @Override
        public void onCompleted() {
            mView.onRequestSuccess();
        }

        @Override
        public void onError(Throwable e) {
            mView.onRequestError(e);
        }

        @Override
        public void onNext(HttpResult<List<StoryBean>> httpResult) {
            List<StoryBean> data = httpResult.getResdata();
            if (httpResult.getResult() == 1 && data != null && data.size() > 0) {
                mView.showCollectionStories(data);
            } else {
                mView.onRequestError(new HttpResultException(2, "数据为空"));
            }
        }
    };

    @Override
    public void getCollectionStories(int page, boolean isHistoryPage) {
        String userToken = DiaryApplication.mInstance.getUserToken();
        if (TextUtils.isEmpty(userToken)) {
            return;
        }
        String pageType = "";
        if (isHistoryPage) {
            pageType = "1";
        }

        NetWork.getInstance()
                .getHomeApi()
                .getCollectionStoryList(pageType, Constant.PAGE_COUNT, page, Constant.OSTYPE, userToken)
                .compose(RxSchedulers.<HttpResult<List<StoryBean>>>io_main())
                .subscribe(collectionObserver);
    }
}
